#!/usr/bin/python2.5
# Copyright 2012 Google Inc.  All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy
# of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distrib-
# uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
# specific language governing permissions and limitations under the License.

"""An HTTP API for fetching and saving map definitions."""

__author__ = 'lschumacher@google.com (Lee Schumacher)'

import simplejson as json

import jsonp
import model

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class Api(webapp.RequestHandler):
  """An HTTP API for fetching and saving map definitions."""

  # pylint: disable-msg=C6409
  def get(self, map_id):
    """Returns the MapRoot JSON for the specified map."""
    map_object = model.Map.Get(map_id)
    if map_object:
      self.response.out.write(jsonp.ToHtmlSafeJson({
          'json': json.loads(map_object.GetCurrentJson() or 'null')
      }))
    else:
      self.error(404)
      self.response.out.write('Map %s not found' % map_id)

  # pylint: disable-msg=C6409
  def post(self, map_id):
    """Stores a new version of the MapRoot JSON for the specified map."""
    map_object = model.Map.Get(map_id)
    if map_object:
      map_object.PutNewVersion(self.request.get('json'))
      self.response.set_status(201)
    else:
      self.error(404)
      self.response.out.write('Map %s not found' % map_id)


def main():
  # Map IDs are generated by base64.urlsafe_b64encode (see model.Map.Create)
  # and they can contain digits, letters, hyphens, and underscores.
  run_wsgi_app(webapp.WSGIApplication([(r'/crisismap/api/([\w-]+)', Api)]))

if __name__ == '__main__':
  main()
